package com.netflexitysolutions.amazonws.ec2.internal.operations;

import java.util.List;

import com.amazonaws.ec2.doc._2009_04_04.PlacementRequestType;
import com.amazonaws.ec2.doc._2009_04_04.RunInstancesResponseType;
import com.amazonaws.ec2.doc._2009_04_04.RunInstancesType;
import com.netflexitysolutions.amazonws.ec2.EC2;
import com.netflexitysolutions.amazonws.ec2.InstanceStartupParameters;
import com.netflexitysolutions.amazonws.ec2.RunningInstance;
import com.netflexitysolutions.amazonws.ec2.internal.ModelUtil;

public class RunInstancesOperation extends OperationExecutor<RunInstancesType, List<RunningInstance>> {

	private InstanceStartupParameters params;
	
	public RunInstancesOperation(EC2 ec2, InstanceStartupParameters params) {
		super(ec2);
		this.params = params;
	}

	@Override
	protected List<RunningInstance> call(RunInstancesType request) {
		// TODO: request.setAdditionalInfo(value);
		request.setBlockDeviceMapping(ModelUtil.toXMLType(params.getBlockDeviceMappings()));
		request.setGroupSet(ModelUtil.toXMLType(params.getSecutiryGroups()));
		request.setImageId(params.getImageId());
		request.setInstanceType(params.getInstanceType() != null ? params.getInstanceType().getName() : null);
		request.setKernelId(params.getKernelId());
		request.setKeyName(params.getKeyName());
		request.setMaxCount(params.getMaxCount());
		request.setMinCount(params.getMinCount());
		request.setMonitoring(ModelUtil.toXMLType(params.getEnableMonitoring()));
		request.setPlacement(ModelUtil.toXMLType(new PlacementRequestType(), params.getAvailabilityZone()));
		request.setRamdiskId(params.getRamdiskId());
		request.setUserData(ModelUtil.toXMLType(params.getUserData()));
		RunInstancesResponseType response = getEC2().getService().runInstances(request);
		if (response.getInstancesSet() == null) {
			return null;
		}
		List<RunningInstance> result = ModelUtil.toDomainType(response);
		return result;
	}

}
